package log

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/fatih/color"
)

var (
	infoColor    = color.New(color.FgWhite).PrintfFunc()
	debugColor   = color.New(color.FgGreen).PrintfFunc()
	warningColor = color.New(color.FgYellow).PrintfFunc()
	errorColor   = color.New(color.FgRed).PrintfFunc()
	logger       *log.Logger
	logFile      *os.File
)

var (
	maxConcurrentTx = 100
	outLog          = make(chan string, maxConcurrentTx)
	mutex           sync.Mutex
	logPath         string
	logLevel        int
)

func Init(path string, level int) {
	logPath = path
	logLevel = level
	// 创建日志文件夹
	err := os.MkdirAll(logPath, os.ModePerm)
	if err != nil {
		log.Fatalf("无法创建日志文件夹: %s", err)
	}
	setCurOutFile()
	// goFunc := func() {
	// 	for {
	// 		message := <-outLog
	// 		if logger != nil {
	// 			logger.Print(message)
	// 		}
	// 		setCurOutFile()
	// 	}
	// }
	// go goFunc()
}

func setCurOutFile() {
	// 获取当前时间
	now := time.Now()
	// 根据当前时间生成日志文件名
	filename := fmt.Sprintf("%d-%02d-%02d_%02d.log", now.Year(), now.Month(), now.Day(), now.Hour())
	logFilePath := filepath.Join(logPath, filename)

	var err error

	_, err = os.Stat(logFilePath)
	if err == nil && logger != nil {
		return
	}
	if logFile != nil {
		logFile.Close()
	}
	// 创建日志文件
	logFile, err = os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("无法创建日志文件: %s", err)
		return
	}
	//defer file.Close()
	// 设置日志输出到文件
	logger = log.New(logFile, "", log.LstdFlags)
}

func Info(format string, a ...interface{}) {
	if logLevel > 1 {
		return
	}
	message := fmt.Sprintf(format, a...)
	logMessage := fmt.Sprintf("[INFO] %s: %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
	infoColor(logMessage)
	// outLog <- logMessage
}

func Debug(format string, a ...interface{}) {
	if logLevel > 2 {
		return
	}
	message := fmt.Sprintf(format, a...)
	logMessage := fmt.Sprintf("[DEBUG] %s: %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
	debugColor(logMessage)
	// outLog <- logMessage
}

func Warning(format string, a ...interface{}) {
	if logLevel > 3 {
		return
	}
	message := fmt.Sprintf(format, a...)
	logMessage := fmt.Sprintf("[WARNING] %s: %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
	warningColor(logMessage)
	// outLog <- logMessage
}

func ErrLog(format string, a ...interface{}) {
	if logLevel > 4 {
		return
	}
	message := fmt.Sprintf(format, a...)
	logMessage := fmt.Sprintf("[ERROR] %s: %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
	errorColor(logMessage)
	// outLog <- logMessage
}
